package com.project.ereader;

import java.util.ArrayList;
import java.util.List;


import com.project.adapters.AdapterArticle;
import com.project.database.SchemaHelper;
import com.project.database.TableArticle;
import com.project.database.TableRss;
import com.project.enums.EnumWebsite;
import com.project.model.RSSBBCFeed;
import com.project.model.RSSBBCFeedItem;
import com.project.services.IServiceDownload;
import com.project.services.IServiceFeed;
import com.project.services.IServiceMediaPlayer;
import com.project.services.ServiceDownload;
import com.project.services.ServiceFeed;
import com.project.services.ServiceMediaPlayer;
import com.project.utility.Global;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

	protected ListView listView = null;
	private String website;
	private String category;
	private String link;
	private SchemaHelper schemaHelper;  
	boolean customTitleSupported;

	private static IServiceMediaPlayer serviceMediaPlayer;
	private static IServiceDownload serviceDownload;
	private AdapterArticle adapterArticle;

	private ServiceConnection mediaPlayerServiceConnection = new ServiceConnection() {

		@Override
		public void onServiceDisconnected(ComponentName name) {
			serviceMediaPlayer = null;
		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			serviceMediaPlayer = (IServiceMediaPlayer) service;
			if(adapterArticle!=null)
				adapterArticle.setServiceMediaPlayer(serviceMediaPlayer);
		}
	};
	
	private ServiceConnection downloadServiceConnection = new ServiceConnection() {

		@Override
		public void onServiceDisconnected(ComponentName name) {
			serviceDownload=null;
		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			serviceDownload = (IServiceDownload) service;
			if(adapterArticle!=null)
				adapterArticle.setServiceDownload(serviceDownload);
		}
	};


	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		customTitleSupported = requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.activity_main);
		listView = (ListView) findViewById(R.id.listView);
		initalize();
	}
	
	@Override
	public void onResume(){
		super.onResume();
		initializeArticles();
	}

	private void initalize() {
		schemaHelper = new SchemaHelper(this);
		Global.initailizeFeeds(this);
		initializeServices();
		initializeArticles();
	}

	private void initializeArticles() {
		Bundle bundle = getIntent().getExtras();
		if (bundle == null) {
			website = String.valueOf(EnumWebsite.BBC);
			List<TableRss> tableRssCollection = schemaHelper
					.listTableRssBy(website);
			if (tableRssCollection.size() > 0) {
				category = tableRssCollection.get(0).getCategory();
				link = tableRssCollection.get(0).getLink();
			}
		} else {
			website = bundle.getString("website");
			category = bundle.getString("category");
			link = bundle.getString("link");
		}

		if (category == null)
			return;

		setWindowTitle("EReader-" + website + "-" + category);
		loadArticleFromDB();
	}

	private void initializeServices() {
		if(serviceMediaPlayer==null){
			Intent serviceMediaPlayerIntent = new Intent(this,ServiceMediaPlayer.class);
			bindService(serviceMediaPlayerIntent, mediaPlayerServiceConnection,BIND_AUTO_CREATE);
		}
		
		if(serviceDownload==null){
			Intent serviceDownloadIntent = new Intent(this,ServiceDownload.class);
			bindService(serviceDownloadIntent, downloadServiceConnection,BIND_AUTO_CREATE);
		}
	}

	private void setWindowTitle(String title) {
		if (customTitleSupported) {
			getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
					R.layout.title_bar);
		}

		TextView myTitleText = (TextView) findViewById(R.id.myTitle);
		if (myTitleText != null) {
			myTitleText.setText(title);
			myTitleText.setBackgroundColor(Color.GREEN);
		}
	}

	private void loadArticleFromDB() {
		List<TableArticle> data = schemaHelper.listTableArticleBy(website,
				category);
		TableArticle[] arrayData = new TableArticle[data.size()];
		data.toArray(arrayData);
		adapterArticle = new AdapterArticle(this,
				R.layout.list_item_article, arrayData);
		adapterArticle.setServiceDownload(serviceDownload);
		adapterArticle.setServiceMediaPlayer(serviceMediaPlayer);
		listView.setAdapter(adapterArticle);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.manageFeed:
			Intent intent = new Intent(this, RSSFeedActivity.class);
			startActivity(intent);
			break;
		case R.id.refresh:
			RequestTask task = new RequestTask(this);
			task.execute(link);
			break;
		case R.id.downloadManage:
			Intent intentDownload = new Intent(this, DownloadManageActivity.class);
			startActivity(intentDownload);
			break;
		case R.id.playList:
			Intent intentPlayList = new Intent(this, PlayListActivity.class);
			startActivity(intentPlayList);
			break;
		case R.id.browser:
			Intent intentBrowser = new Intent(this, BrowserActivity.class);
			startActivity(intentBrowser);
			break;
		case R.id.exit:
			System.exit(0);
			break;
		default:
			break;
		}
		return true;
	}
	
	
	
	class RequestTask extends AsyncTask<String, String, RSSBBCFeed> {
		private MainActivity mainActivity;

		RequestTask(MainActivity mainActivity) {
			this.mainActivity = mainActivity;
		}

		@Override
		protected RSSBBCFeed doInBackground(String... uri) {

			/*
			 * if network is not available
			 * ----------------------------------------------------------
			 */
			if (!Global.isNetworkAvailable(this.mainActivity)) {
				return null;
			}

			IServiceFeed serviceFeed= new ServiceFeed();
			return serviceFeed.AnalysisRss(uri[0]);
		}

		@Override
		protected void onPostExecute(RSSBBCFeed result) {
			if (!Global.isNetworkAvailable(this.mainActivity))
				Toast.makeText(this.mainActivity, "net work is not available.",
						Toast.LENGTH_LONG).show();
			if (result == null)
				return;
			
			List<RSSBBCFeedItem> itemCollection = result.getItemCollection();
			List<TableArticle> articleCollection = new ArrayList<TableArticle>();
			for (RSSBBCFeedItem rssbbcFeedItem : itemCollection) {
				
				/* compose information into tableArticle
	        	----------------------------------------------------------*/
				TableArticle articleItem = new TableArticle();
	    		articleItem.setGuid(rssbbcFeedItem.getGuid());
	    		articleItem.setWebsite(website);
	    		articleItem.setCategory(result.getTitle());
	    		articleItem.setTitle(rssbbcFeedItem.getTitle());
				articleItem.setPubDate(rssbbcFeedItem.getPubDate());
	    		articleItem.setLink(rssbbcFeedItem.getLink());
	    		articleItem.setDescription(rssbbcFeedItem.getDescription());
	    		articleItem.setEnclosureUrl(rssbbcFeedItem.getEnclosureUrl());
	    		articleItem.setEnclosureLength(rssbbcFeedItem.getEnclosureLength());
	    		articleItem.setEnclosureType(rssbbcFeedItem.getEnclosureType());
	    		articleCollection.add(articleItem);
			}
			

	    	String[] guids = new String[articleCollection.size()]; 
	    	for (int i = 0; i < articleCollection.size(); i++) {
	    		guids[i] = articleCollection.get(i).getGuid();
			}
	    	List<String> existGuids = schemaHelper.listExistTableArticleGuid(guids);
	    	for (int i = 0; i < articleCollection.size(); i++) {
				if(existGuids.contains(articleCollection.get(i).getGuid()))
					continue;
				schemaHelper.addTableArticle(articleCollection.get(i));
			}
			
			this.mainActivity.loadArticleFromDB();
			Toast.makeText(this.mainActivity, "Refresh Finished!",
					Toast.LENGTH_LONG).show();
		}

	}

}
